<!-- 租户成员 -->
<template>
  <div>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAddTenantMember"> 添加成员</a-button>
        <a-button type="primary" preIcon="ant-design:edit-outlined" @click="handleOpenInviteLinkList"> 邀请记录</a-button>
        <a-button type="primary" preIcon="ant-design:import-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        <!-- <a-button type="primary" @click="openModal(true, {})" preIcon="ant-design:hdd-outlined"> 回收站</a-button> -->
        <JThirdAppButton biz-type="user" :selected-row-keys="selectedRowKeys" syncToApp syncToLocal
          @sync-finally="onSyncFinally" />
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                移除成员
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
    </BasicTable>
    <!--用户抽屉-->
    <UserForm @register="registerDrawer" @success="handleSuccess"/>
    <!--回收站-->
    <UserRecycleBin @register="registerModal" @success="reload" />
    <!--用户选择弹窗-->
    <SelectUserJoin @register="registerAddUserModal" @select="submitSelectedUser"/>
    <InviteUserList @register="registerInviteLinkList"/>
  </div>
</template>

<script lang="ts" name="tenant-member" setup>
import { ref, computed, unref } from 'vue';
import { BasicTable, TableAction, ActionItem } from '/@/components/Table'
import UserForm from './components/UserForm.vue';
import UserRecycleBin from './components/UserRecycleBin.vue';
import JThirdAppButton from '/@/components/jeecg/thirdApp/JThirdAppButton.vue'
import SelectUserJoin from './SelectUserJoin.vue';
import InviteUserList from './components/InviteUserList.vue';
import { useDrawer } from '/@/components/Drawer';
import { useListPage } from '/@/hooks/system/useListPage'
import { useModal } from '/@/components/Modal';
import { useMessage } from '/@/hooks/web/useMessage';
import { columns, searchFormSchema } from './user.data';
import { listTenantUser, deleteUser, assignUser, batchDeleteUser, getImportUrl, getExportUrl } from './user.api';
import { Icon } from '/@/components/Icon';

// import { usePermission } from '/@/hooks/web/usePermission'
// const { hasPermission } = usePermission();

const { createMessage, createConfirm } = useMessage();

const [registerDrawer, { openDrawer }] = useDrawer();
const [registerModal, { openModal }] = useModal();
const [registerAddUserModal, {openModal: openAddUserModal}] = useModal();
const [registerInviteLinkList, {openModal: openInviteLinkList}] = useModal();

const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  designScope: 'user-list',
  tableProps: {
    title: '用户列表',
    api: listTenantUser,
    bordered: false,
    columns: columns,
    size: 'small',
    formConfig: {
      schemas: searchFormSchema,
    },
    actionColumn: {
      width: 140,
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
    beforeFetch: (params) => {
      return Object.assign({ 'column': 'createTime', 'order': "desc" }, params)
    },
  },
  exportConfig: {
    name: "用户列表",
    url: getExportUrl,
  },
  importConfig: {
    url: getImportUrl
  },
})

const [registerTable, { reload, updateTableDataRecord }, { rowSelection, selectedRowKeys }] = tableContext

const handleAddTenantMember = () => openAddUserModal(true, { inviteWay: 'fromLink', selectPlatformUser: true })
const handleOpenInviteLinkList = () => openInviteLinkList(true, {})

const submitSelectedUser = async (selectRows) => {
  const userIds = selectRows.map(e => e.id)
  console.log('selectRows', selectRows);
  
  await assignUser({userIds}, () => {
    createMessage.success('添加成功')
    reload()
  })
}

async function handleEdit(record: Recordable) {
  openDrawer(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}

async function handleDetail(record: Recordable) {
  openDrawer(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}

async function handleDelete(record) {
  if (checkeUser(record)) {
    createMessage.warning('不允许操作拥有者');
    return;
  }
  await deleteUser({ id: record.id }, reload);
}

async function batchHandleDelete() {
  await batchDeleteUser({ ids: selectedRowKeys.value }, () => {
    selectedRowKeys.value = []
    reload()
  })
}

function handleSuccess({ values }) {
  reload()
  updateTableDataRecord(values.id, values);
  createMessage.success("编辑成功")
}

/**
 *同步钉钉和微信回调
 */
function onSyncFinally({ isToLocal }) {
  // 同步到本地时刷新下数据
  if (isToLocal) {
    reload()
  }
}

function getTableAction(record): ActionItem[] {
  return [
    
    {
      label: '详情',
      onClick: handleDetail.bind(null, record)
    },
    {
      label: '移除',
      ifShow: () => !checkeUser(record),
      color: 'error',
      popConfirm: {
        title: '是否确认移除',
        confirm: handleDelete.bind(null, record)
      },
    },
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
      ifShow: () => !checkeUser(record),
    },
  ]
}

const checkeUser = (record) => {
  // 不能操作租户拥有者, 其余都可以操作
  return record.roleList.map(e => e.roleCode).join(",").includes(('owner'))
}

function getDropDownAction(record): ActionItem[] {
  return [
    
    
  ]
}
</script>

<style scoped></style>
